import time
from apscheduler.schedulers.background import BlockingScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from django_apscheduler.jobstores import DjangoJobStore

from api.api_check import init_and_submit_job
from mysite import db_config
import requests
import logging

# 用于添加定时任务 采用 apscheduler 框架
logger = logging.getLogger('log')

url1 = "http://127.0.0.1:8088/api/check/rule/execute"
data1 = """{"company": "cdxt", "username": "admin", "db": "oracle"}"""

url_datas = ((url1, data1,),)


# -------------------- 可用的定时任务调用方法 start  其他的需要时自定义function即可-------------------------------
# params 中  需要  company（必传）   and   version(可选)


def invoke_job0(params):
    if params is None:
        logging.error("参数为空")
        return
    print('job-time:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    init_and_submit_job(params)


# 定时任务提交，调用方法
def invoke_job1(params):
    if params is None:
        logging.error("参数为空")
        return
    print('job-time:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    init_and_submit_job(params)


def invoke_job2(params):
    if params is None:
        logging.error("参数为空")
        return
    print('job-time:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    init_and_submit_job(params)


def invoke_job3(params):
    if params is None:
        logging.error("参数为空")
        return
    print('job-time:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    init_and_submit_job(params)


def invoke_job4(params):
    if params is None:
        logging.error("参数为空")
        return
    print('job-time:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    init_and_submit_job(params)


def invoke_job5(params):
    if params is None:
        logging.error("参数为空")
        return
    print('job-time:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    init_and_submit_job(params)


def invoke_job6(params):
    if params is None:
        logging.error("参数为空")
        return
    print('job-time:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    init_and_submit_job(params)


def invoke_job7(params):
    if params is None:
        logging.error("参数为空")
        return
    print('job-time:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    init_and_submit_job(params)


def invoke_job8(params):
    if params is None:
        logging.error("参数为空")
        return
    print('job-time:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    init_and_submit_job(params)


def invoke_job9(params):
    if params is None:
        logging.error("参数为空")
        return
    print('job-time:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    init_and_submit_job(params)


# --------------------end-------------------------------

def job():
    """
    通过tuple的方式配置，任务比较少，不用再通过页面接口的方式来配置
    如有需要也可进行调整
    :return:
    """
    print('job-time:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

    for url_data in url_datas:
        url = url_data[0]
        data = url_data[1]
        result = requests.post(url=url, data=data, )
        logger.info(data)
        logger.info(result.content.decode('unicode_escape'))
        result.close()


def run():
    """
    测试用例
    定时调用的方法 统一写在当前文件当中，后面可以通过globals获取到对应的方法
    :return:
    """
    # BackgroundScheduler: 适合于要求任何在程序后台运行的情况，当希望调度器在应用后台执行时使用
    url = db_config.get_sqlalchemy_url()
    scheduler = BlockingScheduler()
    store = SQLAlchemyJobStore(url=url)
    scheduler.add_jobstore(store)

    # 采用corn的方式
    '''
       year (int|str) – 4-digit year
       month (int|str) – month (1-12)
       day (int|str) – day of the (1-31)
       week (int|str) – ISO week (1-53)
       day_of_week (int|str) – number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun)
       hour (int|str) – hour (0-23)
       minute (int|str) – minute (0-59)
       second (int|str) – second (0-59)
               
       start_date (datetime|str) – earliest possible date/time to trigger on (inclusive)
       end_date (datetime|str) – latest possible date/time to trigger on (inclusive)
       timezone (datetime.tzinfo|str) – time zone to use for the date/time calculations (defaults to scheduler timezone)
           
       *    any    Fire on every value
       */a    any    Fire every a values, starting from the minimum
       a-b    any    Fire on any value within the a-b range (a must be smaller than b)
       a-b/c    any    Fire every c values within the a-b range
       xth y    day    Fire on the x -th occurrence of weekday y within the month
       last x    day    Fire on the last occurrence of weekday x within the month
       last    day    Fire on the last day within the month
       x,y,z    any    Fire on any matching expression; can combine any number of any of the above expressions
    '''
    # scheduler.add_job(job, 'cron', day='*', hour='0', minute='10', second='5')
    # 定义需要调用的方法
    job_function = 'job'
    scheduler.add_job(globals().get(job_function), 'cron', day='*', second='*/20', id='xt',
                      name='质量检查', replace_existing=True)
    # scheduler.start()


def job1():
    print("test _ scheduler  add ")


def job2():
    print("test _ scheduler  add ")


def job3():
    print("test _ scheduler  add ")


def get_jobs():
    store = DjangoJobStore()
    jobs = store.get_all_jobs()
    job_list = []
    # comment, command, enable, job_time 不能返回 cur_job.func 否则 导致后面会调用该方法对象
    for cur_job in jobs:
        job_dict = {'id': cur_job.id, 'func_ref': str(cur_job.func_ref),
                    'status': 0 if cur_job.next_run_time is None else 1,
                    'trigger': cur_job.trigger.__str__(),
                    'next_run_time': str(cur_job.next_run_time),
                    'name': cur_job.name}
        job_list.append(job_dict)

    return job_list
